package tree.treerecursion;

import tree.TreeNode;

/**
 * @Classname : BalancedBinaryTree
 * @Description :
 * <a href="https://leetcode.cn/problems/balanced-binary-tree/">110. 平衡二叉树</a>
 * @Author : chentianyu
 * @Date 2022/12/30 21:26
 */


public class BalancedBinaryTree {
    public boolean isBalanced(TreeNode root) {
        return isBalancedAndDepth(root) == -1 ? false : true;
    }

    private int isBalancedAndDepth(TreeNode root) {
        if (root == null) return 0;

        int left = isBalancedAndDepth(root.left), right = isBalancedAndDepth(root.right);
        if (left == -1 || right == -1 || Math.abs(left - right) > 1) return -1;
        return 1 + Math.max(left, right);
    }
}
